import { exec } from 'child_process';
import fs from 'fs/promises'; 
import path from 'path';
import plugin from '../../lib/plugins/plugin.js';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import puppeteer from 'puppeteer';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export class FengYunHelp extends plugin {
  constructor() {
    super({
      name: '风云个人帮助',
      dsc: '风云个人帮助',
      event: 'message',
      priority: 9999,
      rule: [
        { reg: '^#风云个人帮助$', fnc: 'showHelp' }
      ]
    });
    this.bgImageDir = path.join(__dirname, 'bjtu');
    // 设置允许使用的QQ号
    this.allowedUserId = '3669962171';
  }

  // 检查权限
  async checkPermission(e) {
    const userId = e.user_id.toString();
    if (userId !== this.allowedUserId) {
      await e.reply('⚠️ 权限不足，该功能仅限特定用户使用');
      return false;
    }
    return true;
  }

  // 获取随机背景图片
  async getRandomBackgroundImage() {
    try {
      // 确保目录存在
      await fs.access(this.bgImageDir);
      
      // 读取目录中的所有文件
      const files = await fs.readdir(this.bgImageDir);
      
      // 过滤出png文件
      const pngFiles = files.filter(file => 
        file.toLowerCase().endsWith('.png')
      );
      
      if (pngFiles.length === 0) {
        console.log('bjtu目录中没有找到png图片');
        return null;
      }
      
      // 随机选择一张图片
      const randomIndex = Math.floor(Math.random() * pngFiles.length);
      const randomImage = pngFiles[randomIndex];
      
      console.log(`使用背景图片: ${randomImage}`);
      return path.join(this.bgImageDir, randomImage);
    } catch (error) {
      console.error('获取背景图片失败:', error);
      return null;
    }
  }

  // 将图片转换为base64
  async imageToBase64(imagePath) {
    try {
      const imageBuffer = await fs.readFile(imagePath);
      const base64 = imageBuffer.toString('base64');
      return `data:image/png;base64,${base64}`;
    } catch (error) {
      console.error('图片转base64失败:', error);
      return null;
    }
  }

  async showHelp(e) {
    // 检查权限
    const hasPermission = await this.checkPermission(e);
    if (!hasPermission) {
      return true;
    }

    const htmlPath = path.join(__dirname, 'fengyungerenba.html');
    const screenshotPath = path.join(__dirname, 'fengyunger_help.png');

    try {
      await fs.stat(htmlPath);
    } catch (error) {
      if (error.code === 'ENOENT') {
        await e.reply('帮助文件不存在，请检查路径。');
        return true;
      }
      throw error;
    }

    try {
      // 获取随机背景图片
      const bgImagePath = await this.getRandomBackgroundImage();
      let bgImageStyle = '';
      
      if (bgImagePath) {
        const base64Image = await this.imageToBase64(bgImagePath);
        if (base64Image) {
          bgImageStyle = `
            body {
              background: url('${base64Image}') no-repeat center center fixed !important;
              background-size: cover !important;
            }
            .background-effects {
              display: none !important;
            }
          `;
        }
      }

      const browser = await puppeteer.launch({
        headless: true,
        args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']
      });
      const page = await browser.newPage();
      
      // 设置视口大小
      await page.setViewport({ width: 800, height: 1200 });
      
      await page.goto(`file://${htmlPath}`, { waitUntil: 'networkidle2' });
      
      // 如果有背景图片，注入样式
      if (bgImageStyle) {
        await page.addStyleTag({ content: bgImageStyle });
      }
      
      // 截图 - 使用PNG格式，不设置quality参数
      await page.screenshot({ 
        path: screenshotPath, 
        fullPage: true
      });
      await browser.close();

      await e.reply(segment.image(`file://${screenshotPath}`));

      // 删除临时图片
      setTimeout(async () => {
        try {
          await fs.unlink(screenshotPath);
        } catch (error) {
          console.error('删除临时文件失败:', error);
        }
      }, 5000);

    } catch (error) {
      console.error('生成截图失败:', error);
      await e.reply('生成帮助图片失败，请稍后再试~');
    }
    return true;
  }
}